package bidsanity

import grails.converters.JSON

class ListingController {
    def listingService

    def index() { [listingInstanceList: Listing.list(params), listingInstanceTotal: Listing.count()] }

    def show() {
        def listing = Listing.get(params.id)
        if (!listing) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'listing.label', default:  'Listing'), params.id])
            redirect(action: "index")
            return
        }

        [ listing: listing ]
    }

    def create() {
        if (!session.user) {
            flash.message = message(code: 'customer.not.logged.in')
            redirect(action: "index")
            return
        }
        [listingInstance: new Listing(params)]
    }

    def save() {
        if (!session.user) {
            flash.message = message(code: 'customer.not.logged.in')
            redirect(action: "index")
            return
        }
        params.sellerId = Customer.findByEmailAddress(session.user).id
        def listingInstance = listingService.createListing(params)
        if (listingInstance.id == null) {
            flash.message = message(code: 'default.not.created.message', args: [message(code: 'listing.label', default: 'Listing'), params.listingName])
            render(view: "create", model: [listingInstance: listingInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'listing.label', default: 'Listing'), listingInstance.id])
        redirect(action: "show", id: listingInstance.id)
    }
    
    def getBidsForListing(){
        def listing = Listing.get(params.id)
        def bids
        if(listing){
            bids = Bid.mostRecent(listing.id).list()
        }
        else{
            bids = []
        }
        
        def bidString = ""
        def jsonBids = []
        bids.each {
            def bid = [:]
            bid["bidder"] = it.bidder.getNameFromEMail()
            bid["time"] = it.bidTime.time
            bid["amount"] = String.format('$%.2f',it.amount)
            jsonBids.add(bid)
        }

        def bidInfo =[bids: jsonBids, minBid: String.format('$%.2f',listing.minimumBid)]
            
        render bidInfo as JSON
    }

    def myListings() {
        if (session.user){
            def user = Customer.findByEmailAddress(session.user)
            def listings = Listing.findAllBySeller(user)
            return [ listingInstanceList: listings, listingInstanceTotal: listings.size() ]
        }
        else {
            flash.message = message(code: 'listing.not.logged.in')
            redirect(action: "index")
            return
        }
    }
}
